package cn.wangxl.vertx.starter.web;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;

/**
 * 组测样例：
 * 路由匹配规则；
 * 参数提取
 */
public class MappingVerticle extends AbstractVerticle {

  @Override
  public void start(Future<Void> startFuture) throws Exception {
    Vertx vertx = Vertx.vertx();
    HttpServer server = vertx.createHttpServer();

    Router router = Router.router(vertx);

    // localhost:8888/test1/1234/wangx
    // localhost:8888/test1/1234/wangx123
    router.route("/test1/*").handler(ctx -> {
      String aa = "访问通配符匹配路径";
      System.out.println(aa);
      ctx.response().end(aa);
    });

    // localhost:8888/test2/1234/wangx
    router.route("/test2/:id/:name").handler(ctx -> {

      String aa = "提取路径参数";

      String id = ctx.request().getParam("id");
      String name = ctx.request().getParam("name");

      System.out.println(aa+id+name);
      ctx.response().end(aa+id+name);
    });

    // localhost:8888/test3/
    // localhost:8888/oooo/test3
    router.route().pathRegex(".*test3").handler(ctx -> {

      String aa = "使用正则表达式进行路由";

      System.out.println(aa);
      ctx.response().end(aa);
    });

    //localhost:8888/1234/wangx
    router.route().pathRegex("\\/(?<id>[^\\/]+)\\/(?<name>[^\\/]+)").handler(ctx -> {

      String aa = "使用命名的捕获组";
      String id = ctx.request().getParam("id");
      String name = ctx.request().getParam("name");
      System.out.println(aa+id+name);
      ctx.response().end(aa+id+name);
    });

    server.requestHandler(router).listen(8888, http -> {
      if (http.succeeded()) {
        startFuture.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startFuture.fail(http.cause());
      }
    });
  }


  public static void main(String[] args) throws Exception {
    new MappingVerticle().start(Future.future());
  }
}
